package com.example.administrator.daydayappmarket.game.fragment.fragments.toplist.fragment.fragments.online;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.activity.GameChoiceListViewSecondActivity;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.app.App;
import com.example.administrator.daydayappmarket.game.fragment.fragments.toplist.fragment.fragments.single.adapter.GameTopListSingleAdapter;
import com.example.administrator.daydayappmarket.game.fragment.fragments.toplist.fragment.fragments.single.model.GameTopListSingleInfo;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class GameTopListOnlineFragment extends Fragment implements PullToRefreshListView.OnRefreshListener2{


    private ImageView headerImage00;
    private TextView headerText00;
    private TextView headerText01;
    private ImageView headerImage10;
    private TextView headerText10;
    private TextView headerText11;
    private ImageView headerImage20;
    private TextView headerText20;
    private TextView headerText21;

    private RelativeLayout relativeLayout1;
    private RelativeLayout relativeLayout2;
    private RelativeLayout relativeLayout3;

    private View header;


    private List<GameTopListSingleInfo> dataList;
    private List<GameTopListSingleInfo> dataHeader;

    private RequestQueue requestQueue;
    private int page = 1;

    private GameTopListSingleAdapter adapter;

    @InjectView(R.id.fragment_game_classify_single_pullToRefreshListView)
    PullToRefreshListView mFragmentGameClassifySinglePullToRefreshListView;

    public GameTopListOnlineFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataList = new ArrayList<>();
        dataHeader = new ArrayList<>();

        initVolley();

    }

    private void initVolley() {
        page=1;

        requestQueue = App.getApp().getRequestQueue();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, Contacts.URL_GAME_TOPLIST_ONLINE + page,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        if (response != null) {

                            try {
                                JSONArray jsonArray = new JSONArray(response);

                                for (int i = 0; i < jsonArray.length(); i++) {

                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    GameTopListSingleInfo gameTopListSingleInfo =
                                            new GameTopListSingleInfo();

                                    gameTopListSingleInfo.parseJson(jsonObject);



                                    if (i >2) {
                                        dataList.add(gameTopListSingleInfo);
                                    }

                                    if (i < 3) {
                                        dataHeader.add(gameTopListSingleInfo);
                                    }

                                }

                                setHeadView(header,dataHeader);
                                adapter.notifyDataSetChanged();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        stringRequest.setTag("request");
        requestQueue.add(stringRequest);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_game_toplist_single, container, false);
        ButterKnife.inject(this, view);


        adapter = new GameTopListSingleAdapter(dataList, getContext());
        mFragmentGameClassifySinglePullToRefreshListView.setAdapter(adapter);

        header = LayoutInflater.from(getContext()).inflate(R.layout.item_game_toplist_single_header, null);

        mFragmentGameClassifySinglePullToRefreshListView.getRefreshableView().addHeaderView(header);

        if(dataHeader.size()!=0){
            setHeadView(header,dataHeader);
        }

        mFragmentGameClassifySinglePullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mFragmentGameClassifySinglePullToRefreshListView.setOnRefreshListener(this);

        return view;
    }

    private void setHeadView(View header, final List<GameTopListSingleInfo> dataHeader) {

        if(dataHeader!=null){

            relativeLayout1= (RelativeLayout) header.findViewById(R.id.fragment_game_toplist_head_relativeLayout1);
            relativeLayout2= (RelativeLayout) header.findViewById(R.id.fragment_game_toplist_head_relativeLayout2);
            relativeLayout3= (RelativeLayout) header.findViewById(R.id.fragment_game_toplist_head_relativeLayout3);

            headerImage00= (ImageView) header.findViewById(R.id.fragment_game_toplist_head_secondImage);
            headerImage10= (ImageView) header.findViewById(R.id.fragment_game_toplist_head_firstImage);
            headerImage20= (ImageView) header.findViewById(R.id.fragment_game_toplist_head_thirdImage);

            headerText00= (TextView) header.findViewById(R.id.fragment_game_toplist_head_secondNameText);
            headerText01= (TextView) header.findViewById(R.id.fragment_game_toplist_head_secondPersonText);
            headerText10= (TextView) header.findViewById(R.id.fragment_game_toplist_head_firstNameText);
            headerText11= (TextView) header.findViewById(R.id.fragment_game_toplist_head_firstPersonText);
            headerText20= (TextView) header.findViewById(R.id.fragment_game_toplist_head_thirdNameText);
            headerText21= (TextView) header.findViewById(R.id.fragment_game_toplist_head_thirdPersonText);



            headerText10.setText(dataHeader.get(0).getName());
            headerText11.setText(Integer.parseInt(dataHeader.get(0).getDownload_count())/10000+"万人下载");
            Picasso.with(getContext()).load(Contacts.IMAGE_PREFIX+dataHeader.get(0).getIcon_url())
                    .into(headerImage10);

            headerText00.setText(dataHeader.get(1).getName());
            headerText01.setText(Integer.parseInt(dataHeader.get(1).getDownload_count())/10000+"万人下载");
            Picasso.with(getContext()).load(Contacts.IMAGE_PREFIX+dataHeader.get(1).getIcon_url())
                    .into(headerImage00);

            headerText20.setText(dataHeader.get(2).getName());
            headerText21.setText(Integer.parseInt(dataHeader.get(2).getDownload_count())/10000+"万人下载");
            Picasso.with(getContext()).load(Contacts.IMAGE_PREFIX+dataHeader.get(2).getIcon_url())
                    .into(headerImage20);


            relativeLayout1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent=new Intent(getContext(), GameChoiceListViewSecondActivity.class);

                    intent.putExtra("id",dataHeader.get(0).getId());

                    getActivity().startActivity(intent);
                }
            });

            relativeLayout2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent=new Intent(getContext(), GameChoiceListViewSecondActivity.class);

                    intent.putExtra("id",dataHeader.get(1).getId());

                    getActivity().startActivity(intent);
                }
            });

            relativeLayout3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent=new Intent(getContext(), GameChoiceListViewSecondActivity.class);

                    intent.putExtra("id",dataHeader.get(2).getId());

                    getActivity().startActivity(intent);
                }
            });
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);

        requestQueue.cancelAll("request");
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

        dataList.clear();
        dataHeader.clear();
        initVolley();
        refreshView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

        page++;
        requestQueue = App.getApp().getRequestQueue();

        StringRequest stringRequest=new StringRequest(Request.Method.GET, Contacts.URL_GAME_TOPLIST_ONLINE + page, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if(response!=null){

                    try {
                        JSONArray jsonArray = new JSONArray(response);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            GameTopListSingleInfo gameTopListSingleInfo =
                                    new GameTopListSingleInfo();

                            gameTopListSingleInfo.parseJson(jsonObject);

                            dataList.add(gameTopListSingleInfo);
                        }
                        adapter.notifyDataSetChanged();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        stringRequest.setTag("request");
        requestQueue.add(stringRequest);

        refreshView.onRefreshComplete();

    }

}
